import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/',
    component: () => import('@/views/HomeView.vue'),
    meta: { public: true }, // 设为公开页面
    children: [
      {
        path: 'course-list',
        component: () => import('@/views/Course/CourseList.vue'),
        name: 'CourseList',
        meta: { requiresAuth: true, role: 'student' }
      }
    ]
  },
  {
    path: '/student-courses',
    name: 'StudentCourses',
    component: () => import('@/views/Course/StuCourse.vue'),
    meta: { 
      requiresAuth: true,
      role: 'student',
      title: '我的课程'
    }
  },
  {
  path: '/teacher/:id/detail',
  name: 'TeacherDetail',
  component: () => import('@/views/Teacher/TeacherDetail.vue'),
  meta: { requiresAuth: true, role: 'teacher' }
},
  {
  path: '/course/:courseId/video/:chapterId',
  name: 'VideoPlayer',
  component: () => import('@/views/Course/VideoPlayer.vue'),
  meta: {
    requiresAuth: true
  }
},

{
  path: '/classes',
  component: () => import('@/views/Student/class/index.vue'),
  name: 'StudentClasses',
  meta: { title: '我的班级', icon: 'el-icon-school' }
},
  {
  path: '/course-purchase/:id',
  name: 'CoursePurchase',
  component: () => import('@/views/Course/CoursePurchase.vue'),
  meta: { 
    requiresAuth: true,
    title: '课程购买'
  }
},
// router/index.js
{
  path: '/student/shopcart',  // 与菜单项完全一致
  name: 'Cart',
  component: () => import('@/views/Course/CartPage.vue'), // 注意路径大小写
  meta: { 
    requiresAuth: true,
    title: '购物车'
  }
},
{
  path: '/student/selectCourse',  // 与菜单项完全一致
  name: 'SelectCourse',
  component: () => import('@/views/Course/CourseSelectionCenter.vue'), // 注意路径大小写
  meta: { 
    requiresAuth: true,
    title: '选课中心'
  }
},
{
  path: '/student/progress',  // 与菜单项完全一致
  name: 'Progress',
  component: () => import('@/views/Course/StudentCoursesProgress.vue'), // 注意路径大小写
  meta: { 
    requiresAuth: true,
    title: '学习进度'
  }
},
{
  path: '/learn/:id', // 使用id作为参数名
  name: 'CourseDetail',
  component: () => import('@/views/Course/CourseDetail.vue'),
  meta: { 
    requiresAuth: true,
    role: 'student',
    title: '学习课程'
  },
  props: true // 添加这行以确保参数作为props传递
},
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Auth/Login.vue'),
    meta: { public: true }
  },
  {
    path: '/dashboard',
    redirect: () => {
      const authStore = useAuthStore()
      return authStore.userType === 'teacher' ? 
        `/teacher/${authStore.userId}` : 
        `/student/${authStore.userId}`
    }
  },
  {
    path: '/student/:id',
    name: 'student',
    component: () => import('@/views/Student/StudentView.vue'),
    meta: { requiresAuth: true, role: 'student' }
  },
  {
    path: '/student/:id/detail',
    name: 'StudentDetail',
    component: () => import('@/views/Student/StudentDetail.vue'),
    meta: { 
      requiresAuth: true, 
      role: 'student',
      title: '学生详情'
    }
  },
  {
    path: '/teacher/:id',
    name: 'teacher',
    component: () => import('@/views/Teacher/TeacherView.vue'),
    meta: { requiresAuth: true, role: 'teacher' }
  },
  {
    path: '/class',
    redirect: '/class/list',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'list',
        name: 'ClassList',
        component: () => import('@/views/Class/ClassList.vue')
      },
      {
    path: '/detail/:id',
    name: 'ClassInfo',
    component: () => import('@/views/Class/ClassInfo.vue'),
    props: true, // 启用props接收参数
  meta: { 
    requiresAuth: true ,
    stateTransitions: true // 确保路由允许状态传递
  }
  },
      {
        path: 'editor/:id',
        name: 'ClassEditor',
        component: () => import('@/views/Class/InfoEditor.vue'),
        props: true
      },
      {
        path: 'students/:id',
        name: 'ClassStudents',
        component: () => import('@/views/Class/ClassStudents.vue')
      },
      {
        path: 'courses/:id',
        name: 'ClassCourses',
        component: () => import('@/views/Class/ClassCourses.vue')
      },
      {
        path: 'chapters/:id',
        name: 'ClassChapter',
        component: () => import('@/views/Class/CourseMgr.vue'),
        props: true
      }
    ]
  },
  {
    path: '/teacher',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'list',
        name: 'TeacherList',
        component: () => import('@/views/Teacher/TeacherList.vue')
      },
      {
        path: 'editor/:id',
        name: 'TeacherEditor',
        component: () => import('@/views/Teacher/TeacherEditor.vue')
      }
    ]
  },
  {
    path: '/course/practice',
    name: 'PracticeMgr',
    meta: { requiresAuth: true },
    component: () => import('@/views/Course/PracticeMgr.vue')
  },
  {
    path: '/403',
    name: 'forbidden',
    component: () => import('@/views/Error/403.vue'),
    meta: { public: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/Error/404.vue'),
    meta: { public: true }
  },
  {
  path: '/teacher-class',
  meta: { 
    requiresAuth: true,
    role: 'teacher',
    title: '班级管理'
  },
  children: [
    // 班级列表
    {
      path: 'list',
      name: 'TeacherClassList',
      component: () => import('@/views/Teacher/class/TeacherClassInfo.vue'),
      meta: { title: '班级列表' }
    },
    // 班级详情
    {
      path: 'detail/:id',
      name: 'TeacherClassDetail',
      component: () => import('@/views/Teacher/class/TeacherClassDetail.vue'),
      props: true,
      meta: { title: '班级详情' },
      children: [
        {
          path: 'students',
          name: 'TeacherClassStudents',
          component: () => import('@/views/Teacher/class/components/ClassStudents.vue'),
          meta: { title: '学生管理' }
        },
        {
      path: 'courses',
      name: 'TeacherClassCourses',
      component: () => import('@/views/Teacher/class/components/ClassCourses.vue'),
      meta: { title: '课程管理' },
      props: true
    },
        {
          path: 'progress',
          name: 'TeacherClassProgress',
          component: () => import('@/views/Teacher/class/components/ClassProgress.vue'),
          meta: { title: '学习进度' }
        }
      ]
    }
    ,
    // 独立课程管理路由（带权限检查）
    {
      path: 'course-management/:classId',
      name: 'CourseManagement',
      component: () => import('@/views/Teacher/class/CourseManagement.vue'),
      meta: { 
        title: '课程管理',
        requiresPermission: true // 新增权限检查标记
      },
      props: true
    },
  ]
},
  {
    path: '/teacher-class/add',
    name: 'teacherAddClass',
    component: () => import('@/views/Teacher/class/TeacherClassAdd.vue'),
    meta: { requiresAuth: true, role: 'teacher' }
  },
  {
  path: '/teacher-class/detail/students',
  name: 'StudentManagement',
  component: () => import('@/views/Teacher/class/StudentManagement.vue'),
  meta: {
    title: '学生管理',
    requiresAuth: true
  }
},
{
  path: '/my-courses',
  name: 'MyCourses',
  component: () => import('@/views/Teacher/course/MyCourses.vue'),
  meta: { 
    requiresAuth: true,
    role: 'teacher',
    title: '我的课程'
  }
},
{
  path: '/course/create',
  name: 'CreateCourse',
  component: () => import('@/views/Teacher/course/CourseCreate.vue'),
  meta: { 
    requiresAuth: true,
    role: 'teacher',
    title: '创建课程'
  }
},
{
  path: '/practice',
  name: 'Practice',
  component: () => import('@/views/Practices/TeacherPractices.vue'),
  meta: { 
    requiresAuth: true,
    role: 'teacher',
    title: '实践管理'
  }
},
{
    path: '/questions',
    name: 'questions',
    component: () => import('@/views/Practices/QuestionsView.vue'),
  },
  {
    path: '/my-consultation',
    name: 'my-consultations',
    component: () => import('@/views/Practices/MyConsultationsView.vue'),
  },
  {
    path: '/student/practice/list',
    name: 'StuPractice',
    component: () => import('@/views/Student/PracticeSelection.vue'),
  },
  {
    path: '/student/practice/registered',
    name: 'my-practice',
    component: () => import('@/views/Student/MyPractices.vue'),
  },
{
  path: '/course/detail/:id',
  name: 'ChapterManagement',
  component: () => import('@/views/Teacher/course/ChapterManagement.vue'),
  meta: { 
    requiresAuth: true,
    role: 'teacher',
    title: '课程详情'
  },
  props: true
},
{
  path: '/teacher/course/:id',
  name: 'TeacherCourseDetailAll',
  component: () => import('@/views/Teacher/course/TeacherCourseDetailAll.vue'),
  meta: { 
    requiresAuth: true,
    role: 'teacher',
    title: '课程详情'
  },
},
{
  path: '/course/edit/:id',
  name: 'EditCourse',
  component: () => import('@/views/Teacher/course/CourseEdit.vue'),
  meta: { 
    requiresAuth: true,
    role: 'teacher',
    title: '编辑课程'
  },
  props: true
},
{
  path: '/course/chapter/:id',
  name: 'TeacherCourseDetail',
  component: () => import('@/views/Teacher/course/TeacherCourseDetail.vue'),
  meta: { 
    requiresAuth: true,
    role: 'teacher',
    title: '章节管理'
  },
  props: true
},
{
  path: '/video-player',
  name: 'VideoPlayer',
  component: () => import('../views/VideoPlayer.vue'),
  meta: { 
    title: '视频播放',
    requiresAuth: true 
  },
  props: (route) => ({
    courseId: route.query.courseId,
    chapterId: route.query.chapterId
  })
},
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 企业内部系统`
  } else if (to.name === 'Home') {
    document.title = '首页 - 企业内部系统'
  }
  
  // 不需要认证的页面直接放行
  if (to.matched.some(record => record.meta.public)) {
    next()
    return
  }
  
  // 需要认证的页面处理
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (authStore.isAuthenticated()) {
      // 如果用户信息未加载，尝试获取
      if (!authStore.userInfo) {
        try {
          await authStore.fetchUserInfo()
        } catch (error) {
          console.error('获取用户信息失败:', error)
          authStore.resetAuth()
          next({ path: '/login', query: { redirect: to.fullPath } })
          return
        }
      }
      
      // 检查角色权限
      if (to.meta.role && to.meta.role !== authStore.userType) {
        next('/403')
        return
      }
      
      next()
    } else {
      // 未登录重定向到登录页
      next({ path: '/login', query: { redirect: to.fullPath } })
    }
  } else {
    next()
  }
})

export default router